// routes/goods.js 使用的路由处理函数
const superagent = require('superagent')
const cheerio = require('cheerio')

// 导入数据库模型
const { GoodsModel } = require('../db/model')

const createGoods = (req, res) => {
  const { id } = req.params
  const info = require('./info')

  // 获取 url 列表中的某一项
  const item = info[id - 0]
  const category = item.title
  let link = item.link
  
  // 计数用来生成商品 goods_id
  let count = 0

  // 每个链接爬取 100 页
  for (let i = 0; i < 100; i++) {
    let url = link
    
    // 生成分页链接, 第一页不需要添加页码数据
    // 从第二页开始, 根据京东 url 规则拼接
    if (i) url = link + `&page=${2 * i + 1}&s=${i * 60 + 1}&click=0`
    superagent
    .get(url)
    .end((err, data) => {
      if(err) return console.log('=== 报错了 ===', url, err)
      // data.text, 获取爬取到的 html 结构
      const $ = cheerio.load(data.text)
      $('.gl-warp > li').each((index, item) => {

        // 随着遍历向数据库内添加数据
        const dataItem = {
          goods_id: `${ id - 0 + 1 }.00000.${ count++ }`,
          title: $(item).find('.p-name').text().replace(/(\s|\n)/g, ''),
          price: $(item).find('.p-price').find('i').text(),
          img: 'https:' + $(item).find('.p-img').find('img').prop('data-lazy-img'),
          link: 'https:' + $(item).find('.p-img').find('a').prop('href'),
          cate: category
        }
        // 插入数据库
        GoodsModel(dataItem).save()
      })
    })
  }

  res.send({
    code: 1,
    message: '创建成功'
  })
}

const getGoodsList = async (req, res) => {
  const { current } = req.params
  const data = await GoodsModel.find().skip((current - 1) * 12).limit(12)
  res.send({
    code: 1,
    message: '获取商品成功',
    data
  })
}

const getTotal = async (req, res) => {
  // count() 方法返回文档总数
  const total = Math.ceil(await GoodsModel.count() / 12)
  res.send({
    code: 1, 
    message: '获取商品总页数成功',
    total
  })
}

const searchGoods = async (req, res) => {
  let { current, pageSize, cate, word, sortMethod, sortType } = req.body
  let data
  let total
  current = current - 0
  pageSize = pageSize - 0
  const wordReg = new RegExp(word, 'i')
  if (cate === '全部' && !word) {
    data = await GoodsModel.find().skip((current - 1) * pageSize).limit(pageSize)
    total = Math.ceil((await GoodsModel.count()) / pageSize)
  }
  if (cate === '全部' && word) {
    data = await GoodsModel.find({ title: { $regex: wordReg }}).skip((current - 1) * pageSize).limit(pageSize)
    total = Math.ceil((await GoodsModel.find({ title: { $regex: wordReg } }).count()) / pageSize)
  }
  if (cate !== '全部' && !word) {
    data = await GoodsModel.find({ cate }).skip((current - 1) * pageSize).limit(pageSize)
    total = Math.ceil((await GoodsModel.find({ cate }).count()) / pageSize)
  }
  if (cate !== '全部' && word) {
    data = await GoodsModel.find({ cate, title: { $regex: wordReg } }).skip((current - 1) * pageSize).limit(pageSize)
    total = Math.ceil((await GoodsModel.find({ cate, title: { $regex: wordReg } }).count()) / pageSize)
  }
  res.send({
    code: 1,
    message: '获取商品成功',
    data,
    current,
    pageSize,
    total
  })
}

module.exports = {
  createGoods,
  getGoodsList,
  getTotal,
  searchGoods,
}
